package ${projectDomain}.timer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.unswift.annotation.api.Api;
import com.unswift.annotation.api.ApiField;
import ${projectDomain}.adapter.system.SystemCacheRefreshAdapter;
import ${projectDomain}.cache.CacheEnum;
import ${projectDomain}.cache.refresh.ICacheRefreshService;
import ${projectDomain}.pojo.dao.system.cache.refresh.SystemCacheRefreshDataDo;
import ${projectDomain}.pojo.dao.system.cache.refresh.SystemCacheRefreshInsertDo;
import ${projectDomain}.pojo.dao.system.cache.refresh.SystemCacheRefreshSearchDo;
import ${projectDomain}.pojo.dao.system.cache.refresh.SystemCacheRefreshUpdateDo;
import ${projectDomain}.utils.BeanUtils;
import com.unswift.utils.ClassUtils;
import com.unswift.utils.ObjectUtils;
import com.unswift.utils.SystemUtils;

@Component
@Api(value="缓存定时器，用于刷新缓存", author="unswift", date="2023-05-05", version="1.0.0")
public class CacheTimer {

	@Autowired
	@ApiField("系统缓存刷新公共操作")
	private SystemCacheRefreshAdapter systemCacheRefreshAdapter;
	
	@ApiField("spring cloud应用名称")
	@Value("${r'${spring.application.name}'}")
	private String serverName;
	
	@ApiField("spring cloud应用端口")
	@Value("${r'${server.port}'}")
	private String serverPort;
	
	@Scheduled(fixedDelay = 60 * 1000, initialDelay = 30 * 1000)
	public void refreshCache(){
		SystemCacheRefreshSearchDo search=new SystemCacheRefreshSearchDo();
		search.setServer(serverName);
		search.setHostIp(SystemUtils.getHostIp());
		search.setHostPort(serverPort);
		CacheEnum[] cacheList = CacheEnum.values();
		for (CacheEnum cacheEnum : cacheList) {
			if(ObjectUtils.isNotEmpty(cacheEnum.getRefreshBean())){
				search.setCacheKey(cacheEnum.getKey());
				SystemCacheRefreshDataDo cacheRefresh = systemCacheRefreshAdapter.findFirst(search, "缓存信息");
				if(ObjectUtils.isEmpty(cacheRefresh)){
					SystemCacheRefreshInsertDo insert=systemCacheRefreshAdapter.convertPojo(search, SystemCacheRefreshInsertDo.class);
					insert.setCacheType(cacheEnum.getCacheType());
					insert.setRefreshStatus((byte)0);
					insert.setRefreshBean(cacheEnum.getRefreshBean());
					systemCacheRefreshAdapter.save(insert, false);
				}else if(cacheRefresh.getRefreshStatus()==1){
					ICacheRefreshService refreshBean = BeanUtils.getBean(ClassUtils.forName(cacheRefresh.getRefreshBean()));
					refreshBean.refresh(cacheEnum);
					SystemCacheRefreshUpdateDo update=new SystemCacheRefreshUpdateDo();
					update.setId(cacheRefresh.getId());
					update.setRefreshStatus((byte)0);
					systemCacheRefreshAdapter.update(update, false);
				}
			}
		}
	}
	
}
